//
//  PHStoreViewController.m
//  PhnixHome
//
//  Created by Levy Xu on 2017/11/24.
//Copyright © 2017年 Levy Xu. All rights reserved.
//

#import "PHStoreViewController.h"
#import <WebKit/WebKit.h>

#define kHomePage @"http://phnix.5mall.com/"

@interface PHStoreViewController ()<WKUIDelegate, WKNavigationDelegate>
@property(nonatomic, strong) WKWebView *webView;
@property(nonatomic, assign) BOOL isLoaded;
@end

@implementation PHStoreViewController

- (void)initSubviews {
    [super initSubviews];
    
    _webView = [[WKWebView alloc] init];
    _webView.scrollView.bounces = NO;
    _webView.UIDelegate = self;
    _webView.navigationDelegate = self;
    _webView.allowsBackForwardNavigationGestures = YES;
    [self.view addSubview:_webView];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    
    NSString *urlString = kHomePage;
    if ([NDSUD objectForKey:@"kURLPrepareLoading"]) {
        urlString = [NDSUD objectForKey:@"kURLPrepareLoading"];
        [NDSUD removeObjectForKey:@"kURLPrepareLoading"];
        _isLoaded = NO;
    }
    if (!_isLoaded) {
        [self goPage:urlString];
    }
}

-(void)goPage:(NSString *)urlString {
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:urlString]];
//    [request addValue:[self readCurrentCookieWithDomain:urlString] forHTTPHeaderField:@"Cookie"];
    [_webView loadRequest:request];
}

- (NSString *)readCurrentCookieWithDomain:(NSString *)domainStr {
    NSHTTPCookieStorage *cookieJar = [NSHTTPCookieStorage sharedHTTPCookieStorage];
    NSMutableString *cookieString = [[NSMutableString alloc]init];
    for (NSHTTPCookie *cookie in [cookieJar cookies]) {
        [cookieString appendFormat:@"%@=%@;",cookie.name, cookie.value];
    }
    [cookieString deleteCharactersInRange:NSMakeRange(cookieString.length - 1, 1)];
    return cookieString;
}

- (void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    
    if ([_webView isLoading]) {
        [_webView stopLoading];
    }
    [UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
}

- (void)viewDidLayoutSubviews {
    [super viewDidLayoutSubviews];
    CGFloat contentMinY = self.qmui_navigationBarMaxYInViewCoordinator;
    CGFloat contentMaxY = self.qmui_tabBarSpacingInViewCoordinator;
    _webView.frame = CGRectMake(0, contentMinY, APP_WIDTH, SCREEN_HEIGHT - contentMinY - contentMaxY);
}

-(void)reload {
    _isLoaded = NO;
    [_webView reload];
}

-(void)goHomePage {
    _isLoaded = NO;
    [self goPage:kHomePage];
}

-(void)showLeftItem {
    if ([_webView canGoBack]) {
        self.navigationItem.leftBarButtonItem = [UIBarButtonItem qmui_itemWithTitle:NSLocalizedString(@"go_back", nil)
                                                                             target:_webView
                                                                             action:@selector(goBack)];
    } else {
        self.navigationItem.leftBarButtonItem = [UIBarButtonItem qmui_itemWithTitle:NSLocalizedString(@"home_page", nil)
                                                                             target:self
                                                                             action:@selector(goHomePage)];
    }
}

- (void)setupNavigationItems {
    [super setupNavigationItems];
    self.title = NSLocalizedString(@"tab_mall", nil);
    
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemRefresh
                                                                                           target:_webView
                                                                                           action:@selector(reload)];
}

#pragma mark - WKNavigationDelegate
// 页面开始加载时调用
- (void)webView:(WKWebView *)webView didStartProvisionalNavigation:(WKNavigation *)navigation{
    [UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
    [self showEmptyViewWithLoading];
    if (![_webView canGoBack]) {
        self.navigationItem.leftBarButtonItem = nil;
    }
}

// 当内容开始返回时调用
- (void)webView:(WKWebView *)webView didCommitNavigation:(WKNavigation *)navigation{
    [self hideEmptyView];
    [self showLeftItem];
}

// 页面加载完成之后调用
- (void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation{
    [UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
    
    _isLoaded = YES;
    
    /*
    //取出cookie
    NSHTTPCookieStorage *cookieStorage = [NSHTTPCookieStorage sharedHTTPCookieStorage];
    //js函数
    NSString *JSFuncString =
    @"function setCookie(name,value,expires)\
    {\
    var oDate=new Date();\
    oDate.setDate(oDate.getDate()+expires);\
    document.cookie=name+'='+value+';expires='+oDate+';path=/'\
    }\
    function getCookie(name)\
    {\
    var arr = document.cookie.match(new RegExp('(^| )'+name+'=({FNXX==XXFN}*)(;|$)'));\
    if(arr != null) return unescape(arr[2]); return null;\
    }\
    function delCookie(name)\
    {\
    var exp = new Date();\
    exp.setTime(exp.getTime() - 1);\
    var cval=getCookie(name);\
    if(cval!=null) document.cookie= name + '='+cval+';expires='+exp.toGMTString();\
    }";
    
    //拼凑js字符串
    NSMutableString *JSCookieString = JSFuncString.mutableCopy;
    for (NSHTTPCookie *cookie in cookieStorage.cookies) {
        NSString *excuteJSString = [NSString stringWithFormat:@"setCookie('%@', '%@', 1);", cookie.name, cookie.value];
        [JSCookieString appendString:excuteJSString];
    }
    //执行js
    [webView evaluateJavaScript:JSCookieString completionHandler:nil];
    */
}

// 页面加载失败时调用
- (void)webView:(WKWebView *)webView didFailProvisionalNavigation:(WKNavigation *)navigation{
    [UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
    [self showEmptyViewWithText:@"加载失败" detailText:@"请检查网络连接是否正常" buttonTitle:@"重新加载" buttonAction:@selector(reload)];
    _isLoaded = NO;
    [self showLeftItem];
}

// 接收到服务器跳转请求之后调用
- (void)webView:(WKWebView *)webView didReceiveServerRedirectForProvisionalNavigation:(WKNavigation *)navigation{
}

// 在收到响应后，决定是否跳转
- (void)webView:(WKWebView *)webView decidePolicyForNavigationResponse:(WKNavigationResponse *)navigationResponse decisionHandler:(void (^)(WKNavigationResponsePolicy))decisionHandler{
    LOG(@"%@",navigationResponse.response.URL.absoluteString);
    decisionHandler(WKNavigationResponsePolicyAllow);
}

// 在发送请求之前，决定是否跳转
- (void)webView:(WKWebView *)webView decidePolicyForNavigationAction:(WKNavigationAction *)navigationAction decisionHandler:(void (^)(WKNavigationActionPolicy))decisionHandler {
    LOG(@"%@",navigationAction.request.URL.absoluteString);
    decisionHandler(WKNavigationActionPolicyAllow);
}

#pragma mark - WKUIDelegate
// 创建一个新的WebView
- (WKWebView *)webView:(WKWebView *)webView createWebViewWithConfiguration:(WKWebViewConfiguration *)configuration forNavigationAction:(WKNavigationAction *)navigationAction windowFeatures:(WKWindowFeatures *)windowFeatures{
    return [[WKWebView alloc]init];
}

// 输入框
- (void)webView:(WKWebView *)webView runJavaScriptTextInputPanelWithPrompt:(NSString *)prompt defaultText:(nullable NSString *)defaultText initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(NSString * __nullable result))completionHandler{
    completionHandler(@"http");
}

// 确认框
- (void)webView:(WKWebView *)webView runJavaScriptConfirmPanelWithMessage:(NSString *)message initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(BOOL result))completionHandler{
    completionHandler(YES);
}

// 警告框
- (void)webView:(WKWebView *)webView runJavaScriptAlertPanelWithMessage:(NSString *)message initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(void))completionHandler{
    completionHandler();
}

@end
